package de.bazinga.rotw.weapon.grenade;

import com.jme.math.Vector3f;
import com.jme.scene.Controller;

import de.bazinga.rotw.collision.CollisionHandler;
import de.bazinga.rotw.util.GlobalSettings;

public class GrenadeController extends Controller {
	private static final long serialVersionUID = 1L;
	
	private Vector3f direction = null;

	private GrenadeObject granade = null;
	
	private float xSpeed = 5;
	private float ySpeed = 0;
	private float gravitation = 5;
	private float maxDistance = GlobalSettings.MAXBULLETDISTANCE;
	
	private CollisionHandler collHandler = null;
	
	public GrenadeController(GrenadeObject granade, Vector3f direction) {
		this.granade = granade;		
		setDirection(direction);
		
		collHandler = new CollisionHandler(granade);
	}
	
	
	public void update(float tpf) {
		if(!granade.isActive()) return ;
		
		
		granade.getLocalTranslation().addLocal(
						direction.mult(tpf*xSpeed));
		
		granade.getLocalTranslation().addLocal(new Vector3f(0,tpf*ySpeed,0));
		
		this.ySpeed -= tpf*gravitation;
		if(ySpeed > 15) ySpeed = 15;
		
		float distanceTraveled = granade.getStartPosition().distance(granade.getLocalTranslation());
		
		if(distanceTraveled > maxDistance) {
			granade.handleCollision();
			granade.setActive(false);
			return ;
		}
		
		
		// has Collision?
		if(collHandler.collisionWithWall() || 
				collHandler.collisionWithTerrainRay() || 
				collHandler.collisionWithGround() ||
				collHandler.collisionWithObject() ||
				collHandler.collisionWithPhysicsObject()) {
			granade.handleCollision();
			granade.setActive(false);
		}
		
	}

	public void setDirection(Vector3f direction) {
		this.direction = direction.clone();
		

		this.xSpeed = (float)Math.sqrt(direction.getX()*direction.getX() + direction.getZ() * direction.getZ()) * 20;
		this.ySpeed = direction.getY() * 15;
		
		// Normalize
		this.direction.setY(0);
	}

	public Vector3f getDirection() {
		return direction;
	}

}
